package com.banmao.CarlCamp.Day02;

import lombok.extern.slf4j.Slf4j;

/**
 * https://leetcode.cn/problems/squares-of-a-sorted-array/
 */
@Slf4j
public class LC977 {

    public int[] sortedSquares(int[] nums) {
        if (nums == null || nums.length == 0) {
            return nums;
        }

        int[] newNums = new int[nums.length];
        // 左右指针
        int left = 0, right = nums.length - 1;
        int newLast = newNums.length - 1;
        // 平方后，数组的最大值不是在最左边就是在最右边，这是已排序的数组的特性
        while (left <= right) {
            int leftV = nums[left] * nums[left];
            int rightV = nums[right] * nums[right];
            if (leftV < rightV) {
                newNums[newLast--] = rightV;
                right--;
            } else {
                newNums[newLast--] = leftV;
                left++;
            }
        }
        return newNums;
    }

    public static void main(String[] args) {
        int[] nums = new int[] {-7,-3,-1, -0};
        LC977 lc977 = new LC977();
        int[] newNums = lc977.sortedSquares(nums);
        log.info("{}", newNums);
    }

}
